<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="rolesList">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增和编辑的弹层 -->
      <el-dialog
        :title="isEdit?'编辑':'添加'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @closed="hClose"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog=false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible.sync="showAssign"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assignPermission
          v-if="showAssign"
          :role-id="roleId"
          @close="showAssign=false"
          @success="hPerSuccess"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, deleteRole, addRole, editRole } from '@/api/settings'
import assignPermission from './assignPermission.vue'
export default {
  name: 'Settings',
  components: { assignPermission },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      pageParams: {
        page: 1, // 页码值
        pagesize: 2// 每页条数
      },
      rolesList: [], // 角色liebiao
      total: 0, // 总的条数
      showDialog: false, // 控制弹层的显示和隐藏
      isEdit: false,
      showAssign: false, // 分配权限的弹层
      roleId: '' // 分配角色时传的id
    }
  },
  computed: {
    // maxPage() {
    //   return Math.ceil(this.total / this.pageParams.pagesize)
    // },
    // pageFull() {
    //   return this.total % this.pageParams.pagesize === 0
    // }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadRoles()
    },
    // 重置表单
    hClose() {
      // this.roleForm = {
      //   name: '',
      //   description: ''
      // }
      this.$refs.roleForm.resetFields()
    },
    // 实现编辑
    hEdit(row) {
      this.showDialog = true
      this.roleForm = { ...row }
      this.isEdit = true
    },

    // 编辑操作
    async doEdit() {
      try {
        await editRole(this.roleForm)
        this.showDialog = false
        this.loadRoles()
      } catch (error) {
        console.log(error)
      }
    },

    // 点击删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
      })
    },
    // 确定删除
    async doDel(id) {
      try {
        await deleteRole(id)
        this.$message.success('删除成功')
        if (this.rolesList.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 1) {
            this.pageParams.page = 1
          }
        }
        // 2. 重新请求
        this.loadRoles()
        this.$message.success('删除成功!')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取角色信息
    async loadRoles() {
      // 发送请求
      try {
        const res = await getRoles(this.pageParams)
        console.log(res)
        this.rolesList = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
      }
    },

    // 弹层确定按钮
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          // 做具体的添加或编辑动作
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },

    // 点击新增角色
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },

    // 添加角色请求
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res)
        // 将当前的页码值改为最后一页的值
        // this.pageParams.page = this.maxPage
        // if (this.pageFull) {
        //   this.pageParams.page++
        //   this.total++
        // }
        this.total++
        this.pageParams.page = Math.ceil(this.total / this.pageParams.pagesize)
        this.loadRoles()

        this.$message.success('添加成功')
        this.showDialog = false
      } catch (err) {
        console.log(err)
      }
    },

    // 点击分配角色
    hAssign(id) {
      // 记下来id
      this.roleId = id
      this.showAssign = true
    },

    hPerSuccess() {
      // 关闭弹层,刷新页面
      this.showAssign = false
      this.loadRoles()
    }
  }
}
</script>
